package net.edwardstx.hibernateutils;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;

public class HibertateUtilDTOProxyInvocationHandler implements InvocationHandler {

	
	
	static <T extends HibernateDTO> T getDTOByID(T dto, Class<T> classDTO){
		T tMyProxy = dto;
		List<Method> listOfProxyMethods = null;
		for(int intMethodLoopIndex = 0; intMethodLoopIndex < classDTO.getDeclaredMethods().length; intMethodLoopIndex++){
			if(classDTO.getDeclaredMethods()[intMethodLoopIndex].getAnnotation(HibernateUtilProxyMethod.class) != null){
				if(listOfProxyMethods == null){
					listOfProxyMethods = new ArrayList<Method>();
				}
				listOfProxyMethods.add(classDTO.getDeclaredMethods()[intMethodLoopIndex]);
			}
		}
		if(listOfProxyMethods != null)
			Proxy.newProxyInstance(classDTO.getClassLoader(), new Class[] { classDTO }, new HibertateUtilDTOProxyInvocationHandler());
		return tMyProxy;
	}

	@Override
	
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		if("getLineItems".equals(method.getName())) {
			try {
				return method.invoke(proxy, args);
			} catch (Exception exception) {
				// open session
				return method.invoke(proxy, args);
			} finally {
				// if(session open) close session
			}
		} else {
			return method.invoke(proxy, args);
		}
	}

}
